// 初始化示例数据
const initialData = {
    userRoles: [
        {
            id: 'ur1',
            type: 'user-role',
            title: '管理员（校&院）',
            subtitle: '系统管理员、教务',
            active: false
        },
        {
            id: 'ur2',
            type: 'user-role',
            title: '教师',
            subtitle: '课程负责人、任课教师',
            active: false
        },
        {
            id: 'ur3',
            type: 'user-role',
            title: '学生',
            subtitle: '校内、校外、社会',
            active: false
        }
    ],
    functions: [
        { id: 'fn1', type: 'function', title: '门户', active: false },
        { id: 'fn2', type: 'function', title: '展示', active: false },
        { id: 'fn3', type: 'function', title: '共享实验', active: false },
        { id: 'fn4', type: 'function', title: '新闻公告', active: false },
        { id: 'fn5', type: 'function', title: '中心概况', active: false },
        { id: 'fn6', type: 'function', title: '师资队伍', active: false },
        { id: 'fn7', type: 'function', title: '规章制度', active: false },
        { id: 'fn8', type: 'function', title: '视频集锦', active: false },
        { id: 'fn9', type: 'function', title: '特色创新', active: false },
        { id: 'fn10', type: 'function', title: '...', active: false }
    ],
    scenes: [
        {
            id: 'sc0',
            type: 'scene',
            title: '全展示',
            items: [
                { id: 'sci0-1', name: '门户' },
                { id: 'sci0-2', name: '展示' },
                { id: 'sci0-3', name: '共享实验' },
                { id: 'sci0-4', name: '新闻公告' },
                { id: 'sci0-5', name: '中心概况' },
                { id: 'sci0-6', name: '师资队伍' },
                { id: 'sci0-7', name: '规章制度' },
                { id: 'sci0-8', name: '视频集锦' },
                { id: 'sci0-9', name: '特色创新' },
                { id: 'sci0-10', name: '...' },
                { id: 'sci0-11', name: '数据展示' },
                { id: 'sci0-12', name: '登录注册' }
            ],
            active: false
        },
        {
            id: 'sc1',
            type: 'scene',
            title: '资源平台',
            items: [
                { id: 'sci1-1', name: '各学院' },
                { id: 'sci1-2', name: '各学科' },
                { id: 'sci1-3', name: '各公司' },
                { id: 'sci1-4', name: '各类型' }
            ],
            active: false
        },
        {
            id: 'sc2',
            type: 'scene',
            title: '统一管理',
            items: [
                { id: 'sci2-1', name: '系统管理' },
                { id: 'sci2-2', name: '组织管理' },
                { id: 'sci2-3', name: '用户管理' },
                { id: 'sci2-4', name: '...' },
                { id: 'sci2-5', name: '课程管理' }
            ],
            active: false
        },
        {
            id: 'sc3',
            type: 'scene',
            title: '教学管理',
            items: [
                { id: 'sci3-1', name: '课程管理' },
                { id: 'sci3-2', name: '进度跟踪' },
                { id: 'sci3-3', name: '资源维护' },
                { id: 'sci3-4', name: '结果批改' },
                { id: 'sci3-5', name: '开课安排' },
                { id: 'sci3-6', name: '成绩管理' },
                { id: 'sci3-7', name: '任务安排' },
                { id: 'sci3-8', name: '报告管理' }
            ],
            active: false
        },
        {
            id: 'sc4',
            type: 'scene',
            title: '实验教学',
            items: [
                { id: 'sci4-1', name: '课程资源' },
                { id: 'sci4-2', name: '视频' },
                { id: 'sci4-3', name: '课件' },
                { id: 'sci4-4', name: '实验' },
                { id: 'sci4-5', name: '试卷' },
                { id: 'sci4-6', name: '习题' }
            ],
            active: false
        },
        {
            id: 'sc5',
            type: 'scene',
            title: '学生学习',
            items: [
                { id: 'sci5-1', name: '理论学习' },
                { id: 'sci5-2', name: '实验学习' },
                { id: 'sci5-3', name: '智能指导' },
                { id: 'sci5-4', name: '论坛交流' },
                { id: 'sci5-5', name: '学生互评' },
                { id: 'sci5-6', name: '问题库' }
            ],
            active: false
        },
        {
            id: 'sc6',
            type: 'scene',
            title: '师生互动',
            items: [
                { id: 'sci6-1', name: '任务评价' },
                { id: 'sci6-2', name: '答疑讨论' },
                { id: 'sci6-3', name: '论坛交流' }
            ],
            active: false
        },
        {
            id: 'sc7',
            type: 'scene',
            title: '管理',
            items: [
                { id: 'sci7-1', name: '实验维护' },
                { id: 'sci7-2', name: '开放设置' },
                { id: 'sci7-3', name: '实验批改' },
                { id: 'sci7-4', name: '评价管理' }
            ],
            active: false
        },
        {
            id: 'sc8',
            type: 'scene',
            title: '共享学习',
            items: [
                { id: 'sci8-1', name: '自选收藏' },
                { id: 'sci8-2', name: '实验学习' },
                { id: 'sci8-3', name: '实验评价' },
                { id: 'sci8-4', name: '学习统计' }
            ],
            active: false
        },
        {
            id: 'sc9',
            type: 'scene',
            title: '项目申报',
            items: [
                { id: 'sci9-1', name: '申报管理' },
                { id: 'sci9-2', name: '实验对接' },
                { id: 'sci9-3', name: 'ilab对接' },
                { id: 'sci9-4', name: '实验学习' }
            ],
            active: false
        }
    ],
    stats: [
        { id: 'st1', type: 'stats', title: '资源建设数据统计', active: false },
        { id: 'st2', type: 'stats', title: '实验教学应用统计', active: false },
        { id: 'st3', type: 'stats', title: '开放共享应用统计', active: false },
        { id: 'st4', type: 'stats', title: '项目申报数据统计', active: false },
        { id: 'st5', type: 'stats', title: '平台用户数据统计', active: false },
        { id: 'st6', type: 'stats', title: '论坛交流数据统计', active: false }
    ],
    capabilities: [
        { id: 'cp1', type: 'capability', title: '专业学科AI智能体', active: false, logo: '' },
        { id: 'cp2', type: 'capability', title: '管理平台AI智能体', active: false, logo: '' },
        { id: 'cp3', type: 'capability', title: '实验课程AI智能体', active: false, logo: '' },
        { id: 'cp4', type: 'capability', title: '自定义AI智能体', active: false, logo: '' },
        { id: 'cp5', type: 'capability', title: '模型微调', active: false, logo: '' },
        { id: 'cp6', type: 'capability', title: '模型推理', active: false, logo: '' },
        { id: 'cp7', type: 'capability', title: '数据处理', active: false, logo: '' },
        { id: 'cp8', type: 'capability', title: 'prompt构建', active: false, logo: '' },
        { id: 'cp9', type: 'capability', title: 'deepseek', active: false, logo: './images/deepseek.png' },
        { id: 'cp10', type: 'capability', title: '文心一言', active: false, logo: './images/wenxin.png' },
        { id: 'cp11', type: 'capability', title: '通义千问', active: false, logo: './images/tongyi.png' },
        { id: 'cp12', type: 'capability', title: '智谱清言', active: false, logo: './images/zhipu.png' },
        { id: 'cp13', type: 'capability', title: '百川智能', active: false, logo: './images/baichuan.png' },
        { id: 'cp14', type: 'capability', title: '百度大模型', active: false, logo: './images/baidu.png' },
        { id: 'cp15', type: 'capability', title: '讯飞星火', active: false, logo: './images/xunfei.png' },
        { id: 'cp16', type: 'capability', title: '本地化私有模型', active: false, logo: '' }
    ],
    supports: [
        { id: 'su1', type: 'support', title: '标准API', active: false },
        { id: 'su2', type: 'support', title: '应用服务器', active: false },
        { id: 'su3', type: 'support', title: '数据库服务器', active: false },
        { id: 'su4', type: 'support', title: '安全防护', active: false },
        { id: 'su5', type: 'support', title: '文件 | 对象储存服务器', active: false },
        { id: 'su6', type: 'support', title: '操作系统 | 中间件', active: false },
        { id: 'su7', type: 'support', title: '网络和储存', active: false },
        { id: 'su8', type: 'support', title: '云虚实服务器', active: false },
        { id: 'su9', type: 'support', title: '健康监控', active: false }
    ]
};

// 创建Vue应用
const app = Vue.createApp({
    data() {
        return {
            modules: {
                ...JSON.parse(JSON.stringify(initialData)), // 深拷贝初始数据
                customs: [] // 新增自定义组件数组
            },
            dragging: false,
            showModal: false,
            modalTitle: '',
            editingModule: null,
            editingCategory: null,
            showPluginManager: false,
            activePluginTab: 'create',
            newPlugin: {
                name: '',
                description: '',
                icon: 'fas fa-puzzle-piece',
                color: '#6c757d',
                attributes: []
            },
            customPlugins: [],
            importPluginText: ''
        };
    },
    methods: {
        // 拖拽开始
        dragStart(event, type) {
            event.dataTransfer.setData('moduleType', type);
            // 添加拖拽状态
            event.target.classList.add('dragging');
            // 设置拖拽效果
            event.dataTransfer.effectAllowed = 'copy';
        },
        
        // 允许放置
        allowDrop(event) {
            event.preventDefault();
            event.dataTransfer.dropEffect = 'copy';
        },
        
        // 拖拽进入目标区域
        dragEnter(event) {
            event.preventDefault();
            const target = event.target.closest('.architecture-modules');
            if (target) {
                target.classList.add('drag-over');
            }
        },
        
        // 拖拽离开目标区域
        dragLeave(event) {
            event.preventDefault();
            const target = event.target.closest('.architecture-modules');
            if (target && !target.contains(event.relatedTarget)) {
                target.classList.remove('drag-over');
            }
        },
        
        // 放置元素
        drop(event) {
            event.preventDefault();
            const moduleType = event.dataTransfer.getData('moduleType');
            const target = event.target.closest('.architecture-modules');
            
            // 清除拖拽状态
            document.querySelectorAll('.dragging').forEach(el => {
                el.classList.remove('dragging');
            });
            document.querySelectorAll('.drag-over').forEach(el => {
                el.classList.remove('drag-over');
            });
            
            if (!target) return;
            
            let category;
            if (target.classList.contains('scene-modules')) {
                category = 'scenes';
            } else if (target.classList.contains('stats-modules')) {
                category = 'stats';
            } else if (target.classList.contains('capability-modules')) {
                category = 'capabilities';
            } else if (target.classList.contains('support-modules')) {
                category = 'supports';
            } else if (target.classList.contains('custom-modules')) {
                category = 'customs';
            } else if (target.parentElement.classList.contains('function-row')) {
                category = 'functions';
            } else if (target.parentElement.classList.contains('user-role-row')) {
                category = 'userRoles';
            } else {
                return;
            }
            
            this.createNewModule(moduleType, category);
        },
        
        // 创建新模块
        createNewModule(type, category) {
            const id = `new-${type}-${Date.now()}`;
            let newModule = { id, type, active: false };
            
            switch (type) {
                case 'user-role':
                    newModule.title = '新用户角色';
                    newModule.subtitle = '描述';
                    break;
                case 'function':
                    newModule.title = '新功能';
                    break;
                case 'scene':
                    newModule.title = '新场景';
                    newModule.items = [
                        { id: `item-${Date.now()}-1`, name: '新子项1' },
                        { id: `item-${Date.now()}-2`, name: '新子项2' }
                    ];
                    break;
                case 'stats':
                    newModule.title = '新统计项';
                    break;
                case 'capability':
                    newModule.title = '新能力项';
                    newModule.logo = '';
                    newModule.logoSize = 'medium';
                    break;
                case 'support':
                    newModule.title = '新支持项';
                    break;
                case 'custom':
                    newModule.title = '新自定义组件';
                    newModule.icon = 'fas fa-puzzle-piece';
                    newModule.color = '#6c757d';
                    newModule.attributes = {};
                    break;
            }
            
            this.modules[category].push(newModule);
            this.editModule(newModule, category);
        },
        
        // 选择模块
        selectModule(module) {
            // 取消所有模块的选中状态
            Object.keys(this.modules).forEach(category => {
                this.modules[category].forEach(item => {
                    item.active = false;
                });
            });
            
            // 设置当前模块为选中状态
            module.active = true;
        },
        
        // 编辑模块
        editModule(module, category) {
            this.editingModule = JSON.parse(JSON.stringify(module));
            this.editingCategory = category || this.getCategoryByType(module.type);
            
            switch (module.type) {
                case 'user-role':
                    this.modalTitle = '编辑用户角色';
                    break;
                case 'function':
                    this.modalTitle = '编辑功能';
                    break;
                case 'scene':
                    this.modalTitle = '编辑场景';
                    break;
                case 'stats':
                    this.modalTitle = '编辑统计项';
                    break;
                case 'capability':
                    this.modalTitle = '编辑能力项';
                    break;
                case 'support':
                    this.modalTitle = '编辑支持项';
                    break;
                case 'custom':
                    this.modalTitle = '编辑自定义组件';
                    break;
            }
            
            this.showModal = true;
        },
        
        // 删除模块
        deleteModule(module, category) {
            const index = this.modules[category].findIndex(item => item.id === module.id);
            if (index !== -1) {
                this.modules[category].splice(index, 1);
            }
        },
        
        // 添加子项
        addItem() {
            if (!this.editingModule.items) {
                this.editingModule.items = [];
            }
            
            this.editingModule.items.push({
                id: `item-${Date.now()}`,
                name: ''
            });
        },
        
        // 删除子项
        removeItem(index) {
            this.editingModule.items.splice(index, 1);
        },
        
        // 保存模块
        saveModule() {
            const category = this.editingCategory || this.getCategoryByType(this.editingModule.type);
            
            if (!category) return;
            
            const index = this.modules[category].findIndex(item => item.id === this.editingModule.id);
            
            if (index !== -1) {
                // 更新现有模块
                this.modules[category][index] = { ...this.editingModule };
            } else {
                // 添加新模块
                this.modules[category].push({ ...this.editingModule });
            }
            
            this.showModal = false;
            this.editingModule = null;
            this.editingCategory = null;
        },
        
        // 根据类型获取类别
        getCategoryByType(type) {
            switch (type) {
                case 'user-role': return 'userRoles';
                case 'function': return 'functions';
                case 'scene': return 'scenes';
                case 'stats': return 'stats';
                case 'capability': return 'capabilities';
                case 'support': return 'supports';
                case 'custom': return 'customs';
                default: return null;
            }
        },
        
        // 拖拽排序开始
        onDragStart(event) {
            this.dragging = true;
            event.target.classList.add('dragging');
        },
        
        // 拖拽排序结束
        onDragEnd(event) {
            this.dragging = false;
            event.target.classList.remove('dragging');
            // 清除所有拖拽状态
            document.querySelectorAll('.drag-over').forEach(el => {
                el.classList.remove('drag-over');
            });
        },
        
        // 检查是否可以跨区域拖拽
        onMove(event) {
            const { relatedContext, draggedContext } = event;
            const draggedType = draggedContext.element.type;
            const targetCategory = this.getCategoryByContext(relatedContext);
            
            // 允许不同类型的模块在对应的区域中拖拽
            if (targetCategory && this.getCategoryByType(draggedType) === targetCategory) {
                return true;
            }
            
            return false;
        },
        
        // 根据上下文获取类别
        getCategoryByContext(context) {
            if (!context || !context.list) return null;
            
            if (context.list === this.modules.userRoles) return 'userRoles';
            if (context.list === this.modules.functions) return 'functions';
            if (context.list === this.modules.scenes) return 'scenes';
            if (context.list === this.modules.stats) return 'stats';
            if (context.list === this.modules.capabilities) return 'capabilities';
            if (context.list === this.modules.supports) return 'supports';
            if (context.list === this.modules.customs) return 'customs';
            
            return null;
        },
        
        // 处理Logo上传
        handleLogoUpload(event) {
            const file = event.target.files[0];
            if (!file) return;
            
            // 检查文件类型
            if (!file.type.startsWith('image/')) {
                alert('请选择一个图片文件');
                return;
            }
            
            // 检查文件大小 (限制为2MB)
            if (file.size > 2 * 1024 * 1024) {
                alert('图片文件大小不能超过2MB');
                return;
            }
            
            const reader = new FileReader();
            reader.onload = (e) => {
                this.editingModule.logo = e.target.result;
                // 设置默认尺寸
                if (!this.editingModule.logoSize) {
                    this.editingModule.logoSize = 'medium';
                }
            };
            reader.readAsDataURL(file);
        },
        
        // 清除Logo
        clearLogo() {
            this.editingModule.logo = '';
            this.editingModule.logoSize = 'medium';
        },
        
        // 获取Logo尺寸类
        getLogoSizeClass(module) {
            if (!module.logo) return '';
            return module.logoSize || 'medium';
        },
        
        // 插件管理方法
        addAttribute() {
            this.newPlugin.attributes.push({
                name: '',
                type: 'text'
            });
        },
        
        removeAttribute(index) {
            this.newPlugin.attributes.splice(index, 1);
        },
        
        createPlugin() {
            if (!this.newPlugin.name) {
                alert('请输入插件名称');
                return;
            }
            
            const plugin = {
                id: `plugin-${Date.now()}`,
                name: this.newPlugin.name,
                description: this.newPlugin.description,
                icon: this.newPlugin.icon,
                color: this.newPlugin.color,
                attributes: [...this.newPlugin.attributes]
            };
            
            this.customPlugins.push(plugin);
            this.resetNewPlugin();
            alert('插件创建成功！');
        },
        
        resetNewPlugin() {
            this.newPlugin = {
                name: '',
                description: '',
                icon: 'fas fa-puzzle-piece',
                color: '#6c757d',
                attributes: []
            };
        },
        
        importPlugin(event) {
            const file = event.target.files[0];
            if (!file) return;
            
            const reader = new FileReader();
            reader.onload = (e) => {
                try {
                    const plugin = JSON.parse(e.target.result);
                    this.validateAndImportPlugin(plugin);
                } catch (error) {
                    alert('插件文件格式错误');
                }
            };
            reader.readAsText(file);
        },
        
        importPluginFromText() {
            if (!this.importPluginText) {
                alert('请输入插件配置');
                return;
            }
            
            try {
                const plugin = JSON.parse(this.importPluginText);
                this.validateAndImportPlugin(plugin);
                this.importPluginText = '';
            } catch (error) {
                alert('插件配置格式错误');
            }
        },
        
        validateAndImportPlugin(plugin) {
            if (!plugin.name || !plugin.icon) {
                alert('插件配置不完整');
                return;
            }
            
            plugin.id = `plugin-${Date.now()}`;
            this.customPlugins.push(plugin);
            alert('插件导入成功！');
        },
        
        exportPlugin(plugin) {
            const dataStr = JSON.stringify(plugin, null, 2);
            const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr);
            
            const exportFileDefaultName = `${plugin.name}_plugin.json`;
            
            const linkElement = document.createElement('a');
            linkElement.setAttribute('href', dataUri);
            linkElement.setAttribute('download', exportFileDefaultName);
            linkElement.click();
        }
    }
});

// 注册draggable组件
app.component('draggable', window.vuedraggable);

// 挂载应用
app.mount('#app'); 